package com.test.application.linuxState;


import com.sun.management.OperatingSystemMXBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.management.ManagementFactory;
import java.text.DecimalFormat;

@Slf4j
@RestController
@RequestMapping("state")
public class CpuStateLinux {


    /**
     * 获取cpu使用率和内存使用率
     */
    @RequestMapping("/getDevState")
    public StatusDto getDevState() throws Exception {
        StatusDto runQuotaDto = new StatusDto();
        // 获取CPU使用率
        getCpuInfo1(runQuotaDto);
        // 获取内存信息
        getMemoryInfo1(runQuotaDto);
        return runQuotaDto;
    }
    //获取CPU信息
    private void getCpuInfo1(StatusDto  runQuotaDto) {
        OperatingSystemMXBean osBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
        double cpuAverageUsedRatio = osBean.getSystemCpuLoad();
        cpuAverageUsedRatio =  Math.round(cpuAverageUsedRatio * 10000);
        log.info("CPU使用率（万分率）: {}", cpuAverageUsedRatio);
        runQuotaDto.setCpuAverageUsedRatio((int) Math.round(cpuAverageUsedRatio));
    }

    //获取内存信息
    private void getMemoryInfo1(StatusDto runQuotaDto) throws Exception {
        Process process = Runtime.getRuntime().exec("free -b");// TODO 其他方法
        InputStream inputStream = process.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            // 解析输出数据
            if (line.startsWith("Mem:")) {
                String[] split = line.split("\\s+");
                long totalMemory = Long.parseLong(split[1]);// 总内存大小
                runQuotaDto.setMemoryTotal(totalMemory);
                log.info("内存总数: {}字节", totalMemory);
                long usedMemory = Long.parseLong(split[2]);// 已用内存大小
                runQuotaDto.setMemoryUsedCount(usedMemory);
                log.info("内存使用数: {}字节", usedMemory);
                double v = (double) usedMemory / totalMemory;
                log.info("内存使用率: {}%", v);
                runQuotaDto.setMemoryUsedRatio((int) Math.round(v * 10000));

            }
        }
    }

    public static void main(String[] args) {

    }


    private static double convertToMB(String sizeString) {
        double size = 0.0;

        // 提取数字和单位
        String numberPart = sizeString.replaceAll("[^0-9.]", "");
        String unitPart = sizeString.replaceAll("[0-9.]", "");

        // 根据单位进行转换
        if (unitPart.equalsIgnoreCase("G")) {
            size = Double.parseDouble(numberPart) * 1024;
        } else if (unitPart.equalsIgnoreCase("M")) {
            size = Double.parseDouble(numberPart);
        } else if (unitPart.equalsIgnoreCase("K")) {
            size = Double.parseDouble(numberPart) / 1024;
        }

        return size;
    }
}
